

import { _decorator, Component, director, Label } from 'cc';
import i18n from './I18n';
import { aaEvent } from '../common/Enums';
const { ccclass, property, executeInEditMode } = _decorator;

@ccclass('LocalizedLabel')
@executeInEditMode(true)
export class LocalizedLabel extends Component {
    label: Label | null = null;

    @property({ visible: false })
    key: string = '';

    @property({ displayName: 'Key', visible: true })
    get _key() {
        return this.key;
    }
    set _key(str: string) {
        this.key = str;
        this.updateLabel();
    }

    onEnable(): void {
        this.fetchRender();
        director.on(aaEvent.updateLocal,this.updateLabel,this);
    }
    onDisable(): void {
        director.off(aaEvent.updateLocal,this.updateLabel,this);
    }
    fetchRender () {
        let label = this.getComponent(Label);
        if (label) {
            this.label = label;
            this.updateLabel();
            return;
        } 
    }

    updateLabel () {
        let i18nKey = i18n.t(this.key);
        this.label && (this.label.string = i18nKey);
    }
}
